#include <REGX52.H>
#include "Delay.h"
#include "Nixie.h"
#include "MatrixKey.h"

typedef unsigned char uint8;

/*
Matrix Key:
1  2  3  4
5  6  7  8
9  10 11 12
13 14 15 16

Mapping:
C  R  /  =
7  8  9  /
5  6  7  /
1  2  3  0
*/

uint8 numberMapping[] = {99, 99, 99, 99,
							7, 8, 9, 99,
							4, 5, 6, 99,
							1, 2, 3, 0};
uint8 pwd[] = {5, 2, 0, 6, 6, 6};
uint8 TRY_TIMES = 5;

void main() {
	uint8 inputPwd[6] = {0};
	// 0等待输入 1正在输入 2密码错误 3密码正确 4密码锁定 
	uint8 inputType = 0;
	uint8 pressKey;
	uint8 inputCount = 0;
	uint8 inputLen = 0;
	uint8 i;
	
	while (1) {
		
		switch (inputType) {
			case 0: // 等待输入
				ReduceSymbolNixieAt(1);
				break;
			case 1: // 正在输入
				for (i = 0; i < inputLen; i++) {
					Nixie(i + 1, inputPwd[i]);
				}
				if (inputLen < 6)
					ReduceSymbolNixieAt(inputLen + 1);
				break;
			case 2: // 密码错误
				StringErrorNixie();
				break;
			case 3: // 密码正确
				StringPassedNixie();
				continue;
				break;
			case 4: // 密码锁定
				StringLockedNixie();
				continue;
				break;
		}
		
		pressKey = MatrixKey();
		if (pressKey != 0) {
			
			// 按下清空
			if (pressKey == 1) {
				inputType = 0;
				inputLen = 0;
			}
			
			// 按下退位
			if (pressKey == 2) {
				inputLen = inputLen != 0 ? inputLen - 1 : 0;
				if (inputLen == 0)
					inputType = 0;
			}
			
			// 按下确定
			if (pressKey == 4) {
				if (inputLen != 6) {
					inputType = 2;
					inputLen = 0;
				} else {
					// 循环比较
					for (i = 0; i < 6; i++) {
						if (pwd[i] != inputPwd[i]) {
							break;
						}
					}
					if (i == 6) {	// == 6 表示密码正确
						inputType = 3;
					} else {
						inputType = 2;
						inputLen = 0;
					}
				}
				// 统计错误次数
				if (inputType == 2) {
					// 错误次数过多，锁定
					inputCount++;
					if (inputCount == TRY_TIMES)
						inputType = 4;
				}
			}
			
			// 输入密码
			if (inputLen < 6 && numberMapping[pressKey - 1] < 10) {
				inputType = 1;
				inputPwd[inputLen++] = numberMapping[pressKey - 1];
			}
		}
		
	} // while end
	
	
}
